package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.AdDataTO;
import com.chuantou.yuba.api.to.AdTO;
import com.chuantou.yuba.api.to.BaseNewsTypeTO;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.HotNewsDataTO;
import com.chuantou.yuba.api.to.HotNewsTO;
import com.chuantou.yuba.api.to.NewsCommentTO;
import com.chuantou.yuba.api.to.NewsContentTO;
import com.chuantou.yuba.api.to.NewsDetailDataTO;
import com.chuantou.yuba.api.to.NewsDetailTO;
import com.chuantou.yuba.api.to.NewsImageContentTO;
import com.chuantou.yuba.api.to.NewsTO;
import com.chuantou.yuba.api.to.NewsTextContentTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.NewsDetailActivity;
import com.chuantou.yuba.ui.WebViewActivity;
import com.chuantou.yuba.ui.widget.SharePopup;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;

/**
 * 资讯详情
 * 
 * @author dl1001
 * 
 */
public class NewsDetailFragment extends PaginationListFragment<NewsDetailDataTO> implements OnClickListener {
	private static final int[] HOT_NEWS_LAYOUT_IDS = { R.id.hot_news_item_1, R.id.hot_news_item_2 };
	private View mHeaderView;
	private TextView mTitleView;
	private TextView mTimeView;
	private TextView mSourceView;
	private TextView mViewCountView;
	private NewsDetailAdapter mAdapter;
	private NewsTO mNewsTO;
	private int mScreenWidth;
	// 是否已添加收藏
	private boolean mFavorited = false;
	private SharePopup mSharePopup;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mNewsTO = getArguments().getParcelable(Constants.EXTRA_DATA);
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScreenWidth = dm.widthPixels;
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mHeaderView == null) {
			setHasOptionsMenu(true);
			mHeaderView = View.inflate(mContext, R.layout.news_detail_header, null);
			mTitleView = (TextView) mHeaderView.findViewById(R.id.title);
			mTimeView = (TextView) mHeaderView.findViewById(R.id.time);
			mViewCountView = (TextView) mHeaderView.findViewById(R.id.view_vount);
			mSourceView = (TextView) mHeaderView.findViewById(R.id.source);
			mListView.setSelector(new ColorDrawable(Color.TRANSPARENT));
			mListView.setDivider(new ColorDrawable(Color.TRANSPARENT));
			mAdapter = new NewsDetailAdapter();
			mListView.addHeaderView(mHeaderView);
			mListView.setAdapter(mAdapter);
			startRequest();
			requestAdAndHotNews();
		}
		return contentView;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.nickname:
		case R.id.avatar:
			Object tag = v.getTag();
			if (tag != null) {
				String tagString = String.valueOf(tag);
				if (TextUtils.isDigitsOnly(tagString)) {
					ActivityHelper.toProfileActivity(getActivity(), Long.parseLong(tagString));
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_news_detail, menu);
		MenuItem menuItem = menu.findItem(R.id.menu_fav);
		if (mFavorited) {
			menuItem.setTitle(R.string.remove_favorite);
		} else {
			menuItem.setTitle(R.string.add_favorite);
		}
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_fav:
			operateFavorite(!mFavorited);
			return true;
		case R.id.menu_share:
			if (!UiUtil.isFastDoubleClick()) {
				if (mSharePopup != null && mSharePopup.isShowing())
					return true;
				mSharePopup = new SharePopup(getActivity());
				ViewGroup decor = (ViewGroup) getActivity().getWindow().getDecorView();
				mSharePopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			}
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected BaseGsonRequest<NewsDetailDataTO> getRequest(Listener<NewsDetailDataTO> listener, ErrorListener errorListener) {
		String requestUrl = UriHelper.getNewsDetailUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		params.put(UriHelper.PARAMS_ID, mNewsTO == null ? "-1" : String.valueOf(mNewsTO.getId()));
		AccountManager manager = AccountManager.getInstance(mContext);
		if (manager.isLogined()) {
			params.put(UriHelper.PARAMS_UID, String.valueOf(manager.getUserTO().getUid()));
		}
		return new GsonRequest<NewsDetailDataTO>(Method.POST, requestUrl, listener, errorListener, params, NewsDetailDataTO.class);
	}

	private void requestAdAndHotNews() {
		// 请求广告
		String adUrl = UriHelper.getNewsAdUrl();
		HashMap<String, String> adParams = new HashMap<String, String>();
		adParams.put(UriHelper.PARAMS_TYPE, String.valueOf(1));
		GsonRequest<AdDataTO> adRequest = new GsonRequest<AdDataTO>(Method.POST, adUrl, new Listener<AdDataTO>() {

			@Override
			public void onResponse(AdDataTO response) {
				if (response != null) {
					AdTO ad = response.getAd();
					mAdapter.setAd(ad);
					mAdapter.notifyDataSetChanged();
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, adParams, AdDataTO.class);
		RequestManager.startRequest(mContext, adRequest);
		// 请求热门新闻
		String hotNewsUrl = UriHelper.getHotNewsAdUrl();
		HashMap<String, String> hotNewsParams = new HashMap<String, String>();
		hotNewsParams.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(2));
		hotNewsParams.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		GsonRequest<HotNewsDataTO> hotNewsRequest = new GsonRequest<HotNewsDataTO>(Method.POST, hotNewsUrl, new Listener<HotNewsDataTO>() {

			@Override
			public void onResponse(HotNewsDataTO response) {
				if (response != null) {
					List<HotNewsTO> news = response.getNews();
					mAdapter.addHotNews(news);
					mAdapter.notifyDataSetChanged();
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, hotNewsParams, HotNewsDataTO.class);
		RequestManager.startRequest(mContext, hotNewsRequest);
	}

	/**
	 * 操作收藏
	 * 
	 * @param isAdd
	 */
	private void operateFavorite(final boolean isAdd) {
		// 先判断是否已经登录
		AccountManager manager = AccountManager.getInstance(mContext);
		if (manager.isLogined()) {
			UserTO user = manager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
			} else {
				String requestUrl = UriHelper.getOperateFavoriteUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_ACTION, isAdd ? "add" : "del");
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_TYPE, "news");
				params.put(UriHelper.PARAMS_ID, String.valueOf(mNewsTO.getId()));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, requestUrl, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (getActivity() != null) {
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(mContext, R.string.operate_success, Toast.LENGTH_SHORT).show();
									mFavorited = isAdd ? true : false;
									getActivity().supportInvalidateOptionsMenu();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
									} else {
										Toast.makeText(mContext, R.string.operate_failed, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(mContext, R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (getActivity() != null) {
							Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(mContext, request);
			}
		} else {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
		}
	}

	public void reload() {
		load(1);
	}

	@Override
	public void onResponse(NewsDetailDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			NewsContentTO contentTO = null;
			List<NewsCommentTO> comments = null;
			int currentPage = 0;
			int commentCount = 0;
			if (response != null) {
				NewsDetailTO dataTO = response.getData();
				contentTO = dataTO == null ? null : dataTO.getDetail();
				comments = dataTO == null ? null : dataTO.getComments();
				commentCount = dataTO == null ? 0 : dataTO.getCommentCount();
				currentPage = response.getCurrentPage();
				if (currentPage <= 1) {
					mFavorited = dataTO == null ? false : dataTO.isFavorited();
					getActivity().supportInvalidateOptionsMenu();
				}
			}
			if (contentTO != null && currentPage <= 1) {
				// 添加数据
				mTitleView.setText(contentTO.getTitle());
				String time = DateUtils.formatDateTime(mContext, contentTO.getPublishTime() * 1000, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);
				mTimeView.setText(time);
				mViewCountView.setText(getString(R.string.news_view_count, contentTO.getViewCount()));
				String source = contentTO.getSource();
				if (!TextUtils.isEmpty(source)) {
					mSourceView.setText(source);
					mSourceView.setVisibility(View.VISIBLE);
				} else {
					mSourceView.setVisibility(View.GONE);
				}
				mAdapter.clear();
				mAdapter.addData(contentTO.getNewsContents());
				BaseNewsTypeTO hot = new BaseNewsTypeTO();
				hot.setType(BaseNewsTypeTO.TYPE_AD);
				mAdapter.addData(hot);
				if (comments != null && !comments.isEmpty()) {
					BaseNewsTypeTO tagTO = new BaseNewsTypeTO();
					tagTO.setType(BaseNewsTypeTO.TYPE_COMMENT_TAG);
					mAdapter.addData(tagTO);
					mAdapter.setCommentCount(commentCount);
				}
			}
			if (comments != null && !comments.isEmpty()) {
				for (NewsCommentTO to : comments) {
					mAdapter.addData(to);
				}
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.request_error);
	}

	class NewsDetailAdapter extends BaseAdapter {
		private static final int VIEW_TYPE_NEWS_TEXT = 0;
		private static final int VIEW_TYPE_NEWS_IMAGE = 1;
		private static final int VIEW_TYPE_NEWS_COMMENT = 2;
		private static final int VIEW_TYPE_NEWS_COMMENT_TAG = 3;
		private static final int VIEW_TYPE_AD = 4;

		// 评论数
		private int mCommentCount = 0;
		private List<BaseNewsTypeTO> mNews = new ArrayList<BaseNewsTypeTO>();
		private AdTO mAd;
		private List<HotNewsTO> mHotNews = new ArrayList<HotNewsTO>();

		public void setAd(AdTO ad) {
			this.mAd = ad;
		}

		public void addHotNews(List<HotNewsTO> list) {
			mHotNews.clear();
			if (list != null && !list.isEmpty()) {
				mHotNews.addAll(list);
			}
		}

		@Override
		public int getViewTypeCount() {
			return 5;
		}

		public void clear() {
			mNews.clear();
		}

		@Override
		public int getItemViewType(int position) {
			BaseNewsTypeTO to = mNews.get(position);
			if (BaseNewsTypeTO.TYPE_COMMENT.equals(to.getType())) {
				return VIEW_TYPE_NEWS_COMMENT;
			} else if (BaseNewsTypeTO.TYPE_COMMENT_TAG.equals(to.getType())) {
				return VIEW_TYPE_NEWS_COMMENT_TAG;
			} else if (BaseNewsTypeTO.TYPE_IMAGE.equals(to.getType())) {
				return VIEW_TYPE_NEWS_IMAGE;
			} else if (BaseNewsTypeTO.TYPE_AD.equals(to.getType())) {
				return VIEW_TYPE_AD;
			} else {
				return VIEW_TYPE_NEWS_TEXT;
			}
		}

		public void addData(List<BaseNewsTypeTO> data) {
			if (data != null && !data.isEmpty()) {
				mNews.addAll(data);
			}
		}

		public void addData(BaseNewsTypeTO data) {
			if (data != null) {
				mNews.add(data);
			}
		}

		public void setCommentCount(int count) {
			this.mCommentCount = count;
		}

		@Override
		public int getCount() {
			return mNews.size();
		}

		@Override
		public Object getItem(int position) {
			return mNews.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int viewType = getItemViewType(position);
			BaseNewsTypeTO newsTO = mNews.get(position);
			switch (viewType) {
			case VIEW_TYPE_NEWS_TEXT:
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_text, null);
				}
				NewsTextContentTO textTO = (NewsTextContentTO) newsTO;
				TextView contentView = ViewHolder.get(convertView, R.id.text);
				String content = textTO.getContent();
				if (!TextUtils.isEmpty(content)) {
					contentView.setText(Html.fromHtml(content));
				} else {
					contentView.setText(content);
				}
				break;
			case VIEW_TYPE_NEWS_IMAGE:
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_image, null);
				}
				NewsImageContentTO imageTO = (NewsImageContentTO) newsTO;
				NetworkImageView imageView = ViewHolder.get(convertView, R.id.image);
				FrameLayout.LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams();
				int width = mScreenWidth - mContext.getResources().getDimensionPixelSize(R.dimen.news_detail_left_space)
						- mContext.getResources().getDimensionPixelSize(R.dimen.news_detail_right_space);
				int height = (int) (imageTO.getHeight() * 1.0 / imageTO.getWidth() * width);
				layoutParams.width = width;
				layoutParams.height = height;
				imageView.setLayoutParams(layoutParams);
				BitmapBinder.bindNetImage(mContext, imageView, imageTO.getUrl(), R.drawable.default_image_big, false);
				break;
			case VIEW_TYPE_NEWS_COMMENT:
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_comment, null);
				}
				NewsCommentTO commentTO = (NewsCommentTO) newsTO;
				NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
				avatarView.setOnClickListener(NewsDetailFragment.this);
				avatarView.setTag(commentTO.getUid());
				BitmapBinder.bindCircularNetImage(mContext, avatarView, commentTO.getAvatar(), R.drawable.default_avatar_round_small);
				TextView nickNameView = ViewHolder.get(convertView, R.id.nickname);
				nickNameView.setText(commentTO.getUsername());
				nickNameView.setOnClickListener(NewsDetailFragment.this);
				nickNameView.setTag(commentTO.getUid());
				TextView timeView = ViewHolder.get(convertView, R.id.time);
				String time = DateUtils.formatDateTime(mContext, commentTO.getCommentTime() * 1000, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);
				timeView.setText(time);
				TextView commentView = ViewHolder.get(convertView, R.id.comment);
				commentView.setText(commentTO.getContent());
				break;
			case VIEW_TYPE_NEWS_COMMENT_TAG:
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_comment_tag, null);
				}
				TextView tagView = ViewHolder.get(convertView, R.id.tag);
				tagView.setText(Html.fromHtml(getString(R.string.comment_count_tag, mCommentCount)));
				break;
			case VIEW_TYPE_AD:
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_ad, null);
				}
				if (mAd == null && mHotNews.isEmpty()) {
					convertView.setVisibility(View.GONE);
				} else {
					convertView.setVisibility(View.VISIBLE);
					View adLayout = ViewHolder.get(convertView, R.id.ad_layout);
					if (mAd == null) {
						adLayout.setVisibility(View.GONE);
					} else {
						adLayout.setVisibility(View.VISIBLE);
						TextView adTitleView = ViewHolder.get(convertView, R.id.text);
						adTitleView.setText(mAd.getName());
						NetworkImageView adImageView = ViewHolder.get(convertView, R.id.ad_image);
						LinearLayout.LayoutParams imageParams = (android.widget.LinearLayout.LayoutParams) adImageView.getLayoutParams();
						imageParams.height = mScreenWidth / 3;
						BitmapBinder.bindNetImage(mContext, adImageView, mAd.getImage(), R.drawable.default_image_small, false);
						adLayout.setTag(mAd);
						adLayout.setOnClickListener(mAdClickListener);
					}
					View hotNewsTag = ViewHolder.get(convertView, R.id.hot_news_tag);
					View hotNewsLayout = ViewHolder.get(convertView, R.id.hot_news_layout);
					if (mHotNews.isEmpty()) {
						hotNewsTag.setVisibility(View.GONE);
						hotNewsLayout.setVisibility(View.GONE);
					} else {
						hotNewsTag.setVisibility(View.VISIBLE);
						hotNewsLayout.setVisibility(View.VISIBLE);
						for (int i = 0; i < mHotNews.size(); i++) {
							if (i >= HOT_NEWS_LAYOUT_IDS.length) {
								break;
							}
							int layoutId = HOT_NEWS_LAYOUT_IDS[i];
							View itemLayout = ViewHolder.get(convertView, layoutId);
							itemLayout.setVisibility(View.VISIBLE);
							HotNewsTO hotNewTO = mHotNews.get(i);
							TextView hotTitleView = ViewHolder.get(itemLayout, R.id.title);
							hotTitleView.setText(hotNewTO.getTitle());
							TextView hotTimeView = ViewHolder.get(itemLayout, R.id.time);
							String hotTime = DateUtil.getDateString(hotNewTO.getTime() * 1000, DateUtil.PATTERN_YMD);
							hotTimeView.setText(hotTime);
							TextView hotSourceView = ViewHolder.get(convertView, R.id.source);
							hotSourceView.setText(hotNewTO.getSource());
							itemLayout.setOnClickListener(new HotNewsClickListener(hotNewTO));
						}
					}
				}
				break;
			}
			return convertView;
		}
	}

	private OnClickListener mAdClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag != null && tag instanceof AdTO) {
				AdTO ad = (AdTO) tag;
				String link = ad.getLink();
				if (!TextUtils.isEmpty(link)) {
					if (!link.startsWith("http://") && !link.startsWith("https://")) {
						link = "http://".concat(link);
					}
					Intent intent = new Intent(getActivity(), WebViewActivity.class);
					intent.putExtra(Constants.EXTRA_URL, link);
					intent.putExtra(Constants.EXTRA_TITLE, ad.getName());
					startActivity(intent);
				}
			}
		}

	};

	private class HotNewsClickListener implements OnClickListener {
		private HotNewsTO mHotNews;

		public HotNewsClickListener(HotNewsTO news) {
			mHotNews = news;
		}

		@Override
		public void onClick(View v) {
			NewsTO newsTO = new NewsTO();
			newsTO.setId(mHotNews.getId());
			newsTO.setTitle(mHotNews.getTitle());
			newsTO.setSource(mHotNews.getSource());
			newsTO.setPublishTime(mHotNews.getTime());
			Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
			intent.putExtra(Constants.EXTRA_DATA, newsTO);
			startActivity(intent);
		}

	}

}
